package com.company.woye.taiorcheckquestion;

import android.app.DatePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.company.woye.MyApplication;
import com.company.woye.R;
import com.company.woye.base.BaseActivity;
import com.company.woye.internet.KjjPHCallBack;
import com.company.woye.onpackage.activity.OnPackageActivity;
import com.company.woye.taiorcheckSize.TaiorCheckDetailActivity;
import com.company.woye.taiorcheckSize.adapter.TaiorListviewAdapter;
import com.company.woye.taiorcheckSize.bean.TaiorBean;
import com.company.woye.utils.Constans;
import com.company.woye.utils.DBUtil;
import com.company.woye.utils.DataUtils;
import com.company.woye.utils.ScannerManager;
import com.company.woye.utils.Toaster;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.MediaType;

import static com.company.woye.MyApplication.UrlCut;

public class TaiorCheckQuestionActivity extends BaseActivity {

    @BindView(R.id.iv_on_package_back)
    ImageView ivOnPackageBack;
    @BindView(R.id.tv_on_package_back)
    TextView tvOnPackageBack;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.tv_on_package_sure)
    TextView tvOnPackageSure;
    @BindView(R.id.tv_refresh)
    TextView tvRefresh;
    @BindView(R.id.sp_dept)
    Spinner spDept;
    @BindView(R.id.tv_big_dept)
    TextView tvBigDept;
    @BindView(R.id.sp_factory)
    Spinner spFactory;
    @BindView(R.id.ed_make_person)
    TextView edMakePerson;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_LSX)
    Spinner sp_LSX;
    @BindView(R.id.tv_all_DBH)
    TextView tvAllDBH;
    @BindView(R.id.tv_all_part)
    TextView tvAllPart;
    @BindView(R.id.tv_all_piece)
    TextView tvAllPiece;
    @BindView(R.id.tv_all_order_num)
    TextView tvAllOrderNum;
    @BindView(R.id.edit_Barcode)
    EditText editBarcode;
    @BindView(R.id.bt_sure_barcode)
    Button btSureBarcode;
    @BindView(R.id.tv)
    TextView tv;
    @BindView(R.id.lv_detail)
    ListView lvDetail;
    @BindView(R.id.ll_on_package_summary)
    LinearLayout llOnPackageSummary;
    @BindView(R.id.rl)
    RelativeLayout rl;
    private String deptName = "",  bigDept="",cJname = "", LoginUserNo = "", cDate = "", inputId="", inputMan,lsxName;
    String FormType = getClass().getSimpleName();
    private List<String> deptNameList, cJnameList,LsxNameList;
    private ArrayAdapter<String> deptAdapter, cjNameAdapter,lsxNameAdapter;
    private final int MSG_FIND_DEPT = 9001;
    private final int MSG_FIND_CJNAME = 9002;
    private final int MSG_FIND_DATE = 9003;
    private final int MSG_ERROR = 9007;
    private final int MSG_FIND_LSXNAME = 9008;
    private final int MSG_FIND_ZDR = 9009;
    private JSONArray deptJsonarray, cJnameJsonarray, cDateJsonarray,LsxNameJsonArray,ZDRJsonArray;
    private ScannerManager scannerManager;
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };
    List<TaiorBean.DataBean.ZhiCjypcsTagListBean> listBeans = new ArrayList<>();
    TaiorListviewAdapter adapter;
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (scannerManager.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_taior_check_question;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    @Override
    public void initView() {
        IntentFilter inflater = new IntentFilter("finish");
        registerReceiver(receiver, inflater);
        adapter = new TaiorListviewAdapter(this, listBeans);
        lvDetail.setAdapter(adapter);
        cJname = getIntent().getStringExtra("cjName");
        deptName= getIntent().getStringExtra("bmName");
        lsxName = getIntent().getStringExtra("lsx");
        bigDept = getIntent().getStringExtra("bigDept");
        tvBigDept.setText(bigDept);
        inputMan = getIntent().getStringExtra("inputMan");
        inputId = getIntent().getStringExtra("inputId");
        edMakePerson.setText(inputMan);
        LoginUserNo = MyApplication.curLoginUserNo;
        tvDate.setText(DataUtils.getNowData() + " 00:00:00");
        //获取部门
        getDepaName();
//        editBarcode.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
        editBarcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                editBarcode.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.showSoftInput(editBarcode, InputMethodManager.SHOW_FORCED);
            }
        });
        editBarcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null) {
                    if ((event.getAction() == KeyEvent.ACTION_UP) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                        return true;
                    }
                }
                return false;
            }
        });
        editBarcode.requestFocus();
        editBarcode.requestFocusFromTouch();
        //拦截扫描事件
        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code, String deviceName) {
                String nowCode = dealCode(code).trim();
                    editBarcode.setText(nowCode);
                    if (nowCode.length() > 12 || nowCode.length() == 12) {
                        if (deptNameList.size() > 0 && cJnameList.size() > 0&&LsxNameList.size()>0) {
                            nowCode = nowCode.substring(nowCode.length() - 12);
                            Intent intent = new Intent(TaiorCheckQuestionActivity.this, TaiorCheckQuestionDetailActivity.class);
                            intent.putExtra("cjName", spFactory.getSelectedItem().toString());
                            intent.putExtra("txm", nowCode);
                            intent.putExtra("bmName", spDept.getSelectedItem().toString());
                            intent.putExtra("lsx", sp_LSX.getSelectedItem().toString());
                            intent.putExtra("inputMan", inputMan);
                            intent.putExtra("inputId", inputId);
                            startActivity(intent);
                        } else {
                            Toast.makeText(TaiorCheckQuestionActivity.this, "车间或者部门为空", Toast.LENGTH_LONG).show();
                        }
                    }
            }
        }, editBarcode.getContext());


    }

    //保留英文和数字
    private String dealCode(String code) {
        return code.replaceAll("[^a-zA-Z0-9$%]", "");
    }


    private void getLsxName() {
        String sqlFindLsxName = "EXEC  AGV_Basic_GetLsxName @UserNo ='" + LoginUserNo + "'" + ", @cj_name ='" + (cJnameList.size() > 0 ? spFactory.getSelectedItem() : "") + "', @FormType ='" + FormType + "'" + ", @OperType ='GetLsxName'";
        ReadSQLData(sqlFindLsxName, "LsxName");
    }
    private void getMakePersonInfo() {
        //调用WebService过程并处理界面更新;
        String sqlFindLsxName = " EXEC  AGV_Basic_GetCheckID @bmName='"+(deptNameList.size() > 0 ? spDept.getSelectedItem() : "")+"',@cjName='"+(cJnameList.size() > 0 ? spFactory.getSelectedItem() : "")+"',@groupName='"+(LsxNameList.size() > 0 ? sp_LSX.getSelectedItem() : "")+"'";
        ReadSQLData(sqlFindLsxName, "ZDR");
    }

    private void getDepaName() {
        String sqlFindDept = "EXEC  AGV_Basic_GetBbmName @UserNo ='" + LoginUserNo + "'" + ", @FormType ='" + FormType + "'" + ", @OperType ='GetBbmName'";
        ReadSQLData(sqlFindDept, "dept");
    }

    private void getDate() {
        String sqlFindcJname = " EXEC GetCheckKdrq @InputDate='" + tvDate.getText().toString() + "'";
        ReadSQLData(sqlFindcJname, "GetCheckKdrq");

    }

    //获取可用日期
    private void getCjName() {
        String sqlFindcJname = "EXEC  AGV_Basic_GetSewCjName @bmName='"+(deptNameList.size() > 0 ? spDept.getSelectedItem() : "")+"',@UserNo ='" + LoginUserNo + "'" + ", @FormType ='" + FormType + "'" + ", @OperType ='GetSewCjName'";
        ReadSQLData(sqlFindcJname, "cJname");

    }

    private void getList() {
        /**
         * {
         *   "bmName": "制衣四部(2)",
         *   "cjName": "裁剪二工场",
         *   "inputId": "C4201104A",
         *   "kdrq": "2021-11-29 00:00:00",
         *   "token": "7e0daaaed1a1543727122788a4e5398e7c23e88b075a32e3922a6d96b5642db9"
         * }
         */
        String bmName = "";
        String cjName = "";
        if (deptNameList != null && deptNameList.size() > 0) {
            bmName = spDept.getSelectedItem().toString();
        }
        if (cJnameList != null && cJnameList.size() > 0) {
            cjName = spFactory.getSelectedItem().toString();
        }
        String kdrq = cDate;
        JSONObject params = new JSONObject();
        try {
            params.put("bmName", bmName);
            params.put("cjName", cjName);
            params.put("inputId", inputId);
            params.put("kdrq", kdrq);
            params.put("token", Constans.token);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e("提交数据", params.toString());
        Log.e("访问地址", Constans.IP + "szapi/third/BdMlcj/listCjypmlcdjyXx");
        OkHttpUtils.postString()
                .mediaType(MediaType.parse("application/json"))
                .content(params.toString()).url(Constans.IP + "szapi/third/BdMlcj/listCjypmlcdjyXx").build().execute(new KjjPHCallBack<TaiorBean>(TaiorBean.class, TaiorCheckQuestionActivity.this, true) {
            @Override
            public void myError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(TaiorBean response, int id) {
                Toaster.showLong(TaiorCheckQuestionActivity.this, response.getMsg());
                if (response.getMsg().equals("success")) {
                    //填充数据
                    TaiorBean.DataBean data = response.getData();
                    tvAllDBH.setText(data.getCountDbh());
                    tvAllPart.setText(data.getCountBw());
                    tvAllPiece.setText(data.getCountCd());
                    tvAllOrderNum.setText(data.getCountHy());
                    if (data.getZhiCjypcsTagList() != null && data.getZhiCjypcsTagList().size() > 0) {
                        listBeans.clear();
                        listBeans.addAll(data.getZhiCjypcsTagList());
                        adapter.notifyDataSetChanged();
                    }else {
                        listBeans.clear();
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    private void ReadSQLData(String sql, String type) {
        System.out.print("----存储过程:" + sql);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    /**
                     * [{"RoleName":"管理员"},{"RoleName":"调度"},{"RoleName":"装框操作"},{"RoleName":"物流运转"},{"RoleName":"试装箱"}]
                     */
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(UrlCut, sql);
                    System.out.print("----返回结果：" + jsonArray);
                    //部门
                    if (type.equals("dept")) {
                        deptJsonarray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_DEPT;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //车间
                    if (type.equals("cJname")) {
                        cJnameJsonarray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_CJNAME;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //车间
                    if (type.equals("GetCheckKdrq")) {
                        cDateJsonarray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_DATE;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //组别
                    if (type.equals("LsxName")) {
                        LsxNameJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_LSXNAME;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    if (type.equals("ZDR")) {
                        ZDRJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_ZDR;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = MSG_ERROR;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }

            }

        };
        new Thread(run).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //获取部门
                case MSG_FIND_DEPT:
                    if (deptJsonarray != null && deptJsonarray.length() > 0) {
                        deptNameList = new ArrayList<>();
                        for (int i = 0; i < deptJsonarray.length(); i++) {
                            try {
                                deptNameList.add(deptJsonarray.optJSONObject(i).get("BbmName").toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        deptAdapter = new ArrayAdapter<String>(TaiorCheckQuestionActivity.this, android.R.layout.simple_dropdown_item_1line, deptNameList);
                        spDept.setAdapter(deptAdapter);
                        for (int i = 0; i < deptNameList.size(); i++) {
                            if (deptNameList.get(i).equals(deptName)) {
                                spDept.setSelection(i);
                                tvBigDept.setText(spDept.getSelectedItem().toString().substring(0, 4));
                            }
                        }
                        spDept.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                Log.e("选择", spDept.getSelectedItem().toString().substring(0, 4));
                                tvBigDept.setText(spDept.getSelectedItem().toString().substring(0, 4));
                                //获取车间
                                getCjName();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                    }
                    //获取车间
                    getCjName();
                    break;
                //获取车间
                case MSG_FIND_CJNAME:
                    if (cJnameJsonarray != null && cJnameJsonarray.length() > 0) {
                        cJnameList = new ArrayList<>();
                        for (int i = 0; i < cJnameJsonarray.length(); i++) {
                            try {
                                cJnameList.add(cJnameJsonarray.optJSONObject(i).get("CjName").toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        cjNameAdapter = new ArrayAdapter<String>(TaiorCheckQuestionActivity.this, android.R.layout.simple_dropdown_item_1line, cJnameList);
                        spFactory.setAdapter(cjNameAdapter);
                        for (int i = 0; i < cJnameList.size(); i++) {
                            if (cJnameList.get(i).equals(cJname)) {
                                spFactory.setSelection(i);
                            }
                        }
                        spFactory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                                if (isSpinnerFirst) {
//                                    //第一次初始化spinner时，不显示默认被选择的第一项即可
//                                    view.setVisibility(View.INVISIBLE) ;
//                                }
//                                isSpinnerFirst = false ;
                                getLsxName();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });
                    }
                    getLsxName();
                    break;
                //获取日期
                case MSG_FIND_DATE:
                    if (cDateJsonarray != null && cDateJsonarray.length() > 0) {
                        try {
                            if (cDateJsonarray.getJSONObject(0).has("ResultKdrq")) {
                                cDate = cDateJsonarray.getJSONObject(0).getString("ResultKdrq");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    //获取列表
                    getList();
                    break;
                //获取流水线
                case MSG_FIND_LSXNAME:
                    if (LsxNameJsonArray != null && LsxNameJsonArray.length() > 0) {
                        LsxNameList = new ArrayList<>();
                        for (int i = 0; i < LsxNameJsonArray.length(); i++) {
                            try {
                                LsxNameList.add(LsxNameJsonArray.optJSONObject(i).get("lsx").toString());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        lsxNameAdapter = new ArrayAdapter<String>(TaiorCheckQuestionActivity.this, android.R.layout.simple_dropdown_item_1line, LsxNameList);
                        sp_LSX.setAdapter(lsxNameAdapter);
                        for (int i = 0; i < LsxNameList.size(); i++) {
                            if (LsxNameList.get(i).equals(lsxName)) {
                                sp_LSX.setSelection(i);
                            }
                        }
                        sp_LSX.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                //获取列表
                                getMakePersonInfo();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                    }
                    //获取列表
                    getMakePersonInfo();


                    break;
                //获取制单人
                case MSG_FIND_ZDR:
                    if (ZDRJsonArray != null && ZDRJsonArray.length() > 0) {
                        try {
                            if (ZDRJsonArray.getJSONObject(0).has("InputID")){
                                inputId=ZDRJsonArray.getJSONObject(0).get("InputID").toString();
                            }
                            if (ZDRJsonArray.getJSONObject(0).has("InputName")){
                                inputMan=ZDRJsonArray.getJSONObject(0).get("InputName").toString();
                                edMakePerson.setText(inputMan);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    //获取日期
                    getDate();

                    break;
                case MSG_ERROR:
                    Toaster.showLong(TaiorCheckQuestionActivity.this, "连接数据库失败");
                    break;
                default:
                    break;
            }
        }
    };

    @OnClick({R.id.tv_date, R.id.iv_on_package_back, R.id.tv_on_package_back, R.id.tv_refresh, R.id.bt_sure_barcode})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_on_package_back:
            case R.id.tv_on_package_back:
                finish();
                break;
            case R.id.tv_date:
                Calendar calendar = Calendar.getInstance();
                DatePickerDialog datePickerDialog = new DatePickerDialog(TaiorCheckQuestionActivity.this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        String month;
                        if ((monthOfYear + 1) < 10) {
                            month = "0" + (monthOfYear + 1);
                        } else {
                            month = (monthOfYear + 1) + "";
                        }
                        tvDate.setText(year + "-" + (month) + "-" + dayOfMonth + " 00:00:00");
                        getDate();
                    }
                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                datePickerDialog.show();
                break;
            case R.id.tv_refresh:
                getList();
                break;
            case R.id.bt_sure_barcode:
                String nowCode = editBarcode.getText().toString();
                if (nowCode.length() > 12 || nowCode.length() == 12) {
                    if (deptNameList.size() > 0 && cJnameList.size() > 0&&LsxNameList.size()>0) {
                        nowCode = nowCode.substring(nowCode.length() - 12);
                        Intent intent = new Intent(TaiorCheckQuestionActivity.this, TaiorCheckQuestionDetailActivity.class);
                        intent.putExtra("cjName", spFactory.getSelectedItem().toString());
                        intent.putExtra("txm", nowCode);
                        intent.putExtra("bmName", spDept.getSelectedItem().toString());
                        intent.putExtra("lsx", sp_LSX.getSelectedItem().toString());
                        intent.putExtra("inputMan", inputMan);
                        intent.putExtra("inputId", inputId);
                        startActivity(intent);
                    } else {
                        Toast.makeText(TaiorCheckQuestionActivity.this, "车间或者部门为空", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(TaiorCheckQuestionActivity.this, "请输入条形码", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }
}
